package com.gui.profile.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.gui.profile.service.SlowApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.concurrent.TimeUnit;

@Service
public class SlowApiServiceImpl implements SlowApiService {


    @Autowired
    private RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(SlowApiServiceImpl.class);

    @Override
    public void slow() {
        cost500ms();
        cost800ms();
        cost2000ms();
        cost1000ms();
        testApi();
        readFile();
    }


    private void testApi() {
        for (int i = 0; i < 3; i++) {
            long startTime = System.currentTimeMillis();
            ResponseEntity<String> entity = restTemplate.getForEntity("https://uapis.cn/api/say", String.class);
            if (HttpStatus.OK.equals(entity.getStatusCode())) {
                logger.info(entity.getBody());
            } else {
                logger.error("error");
            }
            logger.info("cost time: {}", System.currentTimeMillis() - startTime);
        }
    }

    public void cost500ms() {
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (Exception e) {
            logger.error("sleep exception...");
        }
    }

    public void cost800ms() {
        try {
            TimeUnit.MILLISECONDS.sleep(800);
        } catch (Exception e) {
            logger.error("sleep exception...");
        }
    }

    public void cost2000ms() {
        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (Exception e) {
            logger.error("sleep exception...");
        }
    }

    public void cost1000ms() {
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (Exception e) {
            logger.error("sleep exception...");
        }
    }

    private void readFile() {
        long startTime = System.currentTimeMillis();
        String path = "D:\\software\\program\\yourkit\\YourKit_Java_Profiler_2022.9_B171.rar";
        byte[] bytes = FileUtil.readBytes(new File(path));//内存读写流 不用回收关闭
        ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(bytes);
        IoUtil.read(byteArrayInputStream, CharsetUtil.UTF_8);
        logger.info("read file cost time: {}", System.currentTimeMillis() - startTime);
    }

}
